from django.core.management.base import BaseCommand, CommandError
from optparse import make_option

from django.conf import settings
from django.db import connection, models
from time import strftime
import time
import cPickle

from djfacet.constants import *

from djfacet.facetviews import *
from djfacet.models import CachedFacetedManager
from djfacet.fb_utils.utils import djfacetlog


##################
#  Tue Sep 14 15:29:58 CEST 2010
#	THis command needs to be run BEFORE using the DB cache functionalities on the browser!!!!
#
##################


# EG:
# bash-3.2$ python manage.py djfacet_store_facetmanager



class Command(BaseCommand):
	args = '<no args>'
	help = 'Saves the faceted manager instance in the database, using pickle'

	# make_option requires options in optparse format
	# option_list = BaseCommand.option_list	 + (
	#			  )


	def handle(self, *args, **options): 
		"""
		args - 
		options - 
		"""

		# feedback:
		print "\n\n++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\n%s\nSTARTING CACHING FM using pickle"	 % strftime("%Y-%m-%d %H:%M:%S")	
		print "++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\n"
		
		
		# now the commands for creating the FM, and pickling it

		loaded_facet_groups = []
		# facets_for_template = {}
		facets_for_template = []
	
		# load facet specs 
		# 1: create groups from SPECS.facet_groups	//	2: load facets into groups using SPECS.facetslist
		for x in reversed(sorted(DJ_SPECS.facet_groups, key=lambda (k): k['position'])):
			if x['default']:
				loaded_facet_groups.append(FacetsGroup(x['uniquename'], x['label'], x['position'])) 
		for g in loaded_facet_groups:
			g.buildfacets_fromspecs(DJ_SPECS.facetslist)
	
		result_types = DJ_SPECS.result_types 
	
		# initialize the faceted manager 
	
		FM_INSTANCE = FacetedManager(loaded_facet_groups, result_types)
		
		CachedFacetedManager.objects.all().delete()  # empty it first: there must be one line only

		c = CachedFacetedManager(manager=FM_INSTANCE)
		c.save()
		
						
		print '\nSuccessfully cached FM object'
